package com.flow.framework.api.doc.service.web.impl;

import com.flow.framework.api.doc.properties.FrameworkApiDocConfigProperties;
import com.flow.framework.common.util.verify.VerifyUtil;
import com.flow.framework.web.service.web.IResponseBodyAdviceService;
import lombok.RequiredArgsConstructor;

import java.util.Collection;

/**
 * swagger响应body处理
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2023/2/25
 */
@RequiredArgsConstructor
public class SwaggerResponseBodyAdviceServiceImpl implements IResponseBodyAdviceService {

    private final FrameworkApiDocConfigProperties frameworkApiDocConfigProperties;

    /**
     * swagger相关返回对象的包路径
     */
    private static final String EXCLUDE = "springfox.documentation";

    /**
     * 是否匹配
     *
     * @param contextPath contextPath
     * @param method      method
     * @param uriPath     uriPath
     * @param body        body
     * @return
     */
    @Override
    public boolean isMatch(String contextPath, String method, String uriPath, Object body) {
        if (null == body) {
            return false;
        }
        if (frameworkApiDocConfigProperties.isEnableApiDoc()) {
            if (body.getClass().getName().startsWith(EXCLUDE)) {
                return true;
            } else if (body instanceof Collection) {
                Collection<?> collection = (Collection<?>) body;
                if (VerifyUtil.isEmpty(collection)) {
                    return false;
                }
                Object o = collection.iterator().next();
                return o.getClass().getName().startsWith(EXCLUDE);
            }
        }
        return false;
    }

    @Override
    public Object getResponseBody(Object body) {
        return body;
    }
}